package com.bestv.search.engine.servlet;

import com.bestv.search.engine.command.IndexCommand;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

public final class IndexServlet extends javax.servlet.http.HttpServlet implements javax.servlet.Servlet {
    private static final long serialVersionUID = 5149594107299981672L;
    protected final Log log = LogFactory.getLog(getClass());
    private WebApplicationContext wac;

    public IndexServlet() {
        super();
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doExecute(request, response);
    }

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException,
            IOException {
        doExecute(request, response);
    }

    public void init() throws ServletException {
        super.init();
        ServletContext application = getServletContext();
        wac = WebApplicationContextUtils.getWebApplicationContext(application);
    }

    public void doExecute(HttpServletRequest request, HttpServletResponse response) throws ServletException,
            IOException {
        IndexCommand index = (IndexCommand) wac.getBean("index");
        if (index.getCoreDevice().isCanStartIncrementIndexThread()) {
            response.getWriter().write(index.index());
            return;
        }
        String reqStr = request.getParameter("forceindex");
        if (reqStr == null) {
            log.debug("The increasing index thread is running, waiting until the thread finished......");
            response.getWriter().write("The thread is busy, please try later! ");
            return;
        }
        if (reqStr.equals("true")) {
            response.getWriter().write(index.index(true));
            return;
        }
    }

    @Override
    public void destroy() {
        super.destroy();
    }
}